package com.pai4j.netty.server.service.redis;

import com.pai4j.netty.server.config.RedisPool;
import redis.clients.jedis.Jedis;

import java.util.function.Consumer;
import java.util.function.Function;

public abstract class AbstractRedisService {

    public static void del(String key) {

        executeAndRelease(jedis -> jedis.del(key));
    }

    public static void expire(String key, long seconds) {

        executeAndRelease(jedis -> jedis.expire(key, seconds));
    }

    public static void executeAndRelease(Consumer<Jedis> consumer) {
        try (Jedis jedis = RedisPool.getJedisResource()) {
            consumer.accept(jedis);
        }
    }

    public static <T> T executeAndReleaseWithReturn(Function<Jedis, T> function) {
        try (Jedis jedis = RedisPool.getJedisResource()) {
            return function.apply(jedis);
        }
    }
}
